package jp.co.sharp.android.parents.kidsguard.activity.setting;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.android.bluetooth.parentble.ParentBleTransfer;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.adapter.ContactOptAdapter;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.ContactListDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

/**
 * 連絡先選択
 */
public class ContactOptActivity extends Activity {

    private App mApp;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private final static int REQUEST_CODE = 100;
    private final static int REQUEST_CODE2 = 101;
    private ParentBleTransfer mParentBleTransfer;
    private Intent mIntent;
    private KidInfoEntity mKidInfoEntity;

    private ListView mContactList;
    // 0: lock, 0: init , 1: getInfo , 2: setInfo, 3 :end
    private int mViewProcess = 0;
    private Integer mPosition;
    private int mPageSerialNum;
    private boolean mUnReceiver = true;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    private static final String TAG = "TAG";
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;
    private static final int PAGE_EDIT_REOPEN = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "ContactOptActivity_onCreate");
        setContentView(R.layout.activity_contact_opt);

        mApp = (App)getApplication();
        initReceiver();
        initActivity();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "ContactOptActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    Message msg = new Message();
                    msg.what = PAGE_EDIT_REOPEN;
                    handler.sendMessage(msg);
                }
                mSystemHomeFlag = false;
            }
            mUnReceiver = false;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(this.TAG, "ContactOptActivity_onStart");
        synchronized (mSyncLock) {
            mApp.setAppStatus(Constants.APP_STATUS_INIT);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "ContactOptActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ContactOptActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
    }

    private void initActivity() {
        Log.i(TAG, "ContactOptActivity_initActivity");
        this.mIntent = getIntent();
        mPosition = mIntent.getIntExtra("position",0);
        mPageSerialNum = mIntent.getIntExtra(Constants.KEY_PAGE_SERIAL_NUM, PageSerialNumConstants.PAGE_SERIAL_CONTACT);
        this.mKidInfoEntity = mApp.findKidInfoBySelect();
        ImageView addContact = (ImageView)findViewById(R.id.addContact);
        addContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // ページジャンプ
                mPageJumpFlag = true;
                Intent intent = new Intent();
                intent.setClass(ContactOptActivity.this, ContactOptAddActivity.class);
                intent.putExtra(Constants.KEY_PAGE_SERIAL_NUM, mPageSerialNum);
                startActivityForResult(intent, REQUEST_CODE2);
            }
        });
        mContactList = (ListView)findViewById(R.id.contactList);

        // Dlg
        String message = "キッズケータイから情報を取得しています...";
        mDealWithWaitingDlg = new DealWithWaitingDlg(ContactOptActivity.this, R.style.commonDlg, message, true);
        mDealWithWaitingDlg.show();
        // init
        sendGetToKid();
    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        Log.i(TAG, "ContactOptActivity_initReceiver");
        IntentFilter filter = new IntentFilter();
        // ロック画面
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 画面を開く
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App)getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    private void sendGetToKid() {
        Log.i(TAG, "ContactOptActivity_sendGetToKid");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_GET_CONTACTS);
            jsonObject.put("data", JSONObject.NULL);
            mViewProcess = Constants.SEND_KID_GET_INFO;
            new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, jsonObject, mPageSerialNum).start();
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                mPageSerialNum).start();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            Message msg = new Message();
                            msg.what = PAGE_EDIT_REOPEN;
                            handler.sendMessage(msg);
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                        mSystemHomeFlag = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                mPageSerialNum).start();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);
                        // TODO Mimamori
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                mPageSerialNum).start();

                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(ContactOptActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        mApp.updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactOptActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();

                                // ページジャンプ
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(ContactOptActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {
                        switch(mViewProcess) {
                            case Constants.SEND_KID_IS_USING:
                                break;
                            case Constants.SEND_KID_ENTER:
                                mEditReopening = false;
                                handler.sendEmptyMessage(0);
                                break;
                            case Constants.SEND_KID_GET_INFO:
                                break;
                            case Constants.SEND_KID_SET_INFO:
                                break;
                            case Constants.SEND_KID_EXIT:
                                break;
                        }
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);
                    if (RequestMethodConstants.METHOD_GET_CONTACTS.equals(jsonObject.getString("method"))) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        List<ContactListDto> lsContactListDto = new ArrayList<>();
                        for (int i =0; i < jsonArray.length(); i++){
                            JSONObject jsonItem = jsonArray.getJSONObject(i);
                            ContactListDto contactListDto = new ContactListDto();
                            contactListDto.setId(jsonItem.getInt("id"));
                            contactListDto.setName(jsonItem.getString("name"));
                            contactListDto.setPhone(jsonItem.getString("phone"));
                            contactListDto.setYomi(jsonItem.getString("yomi"));
                            contactListDto.setPortrait(jsonItem.getString("portrait"));
                            lsContactListDto.add(contactListDto);
                        }
                        viewContactList(lsContactListDto);
                        handler.sendEmptyMessage(0);
                    } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(jsonObject.getString("method"))) {
                        String message = "キッズケータイが操作されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactOptActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                // ページジャンプ
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(ContactOptActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    } else if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getJSONObject("data").getString("state").equals(Constants.IS_USING_OK)) {
                            mViewProcess = Constants.SEND_KID_ENTER;
                            new BusinessThread(Constants.SEND_KID_ENTER, mParentBleTransfer, mKidInfoEntity, null, mPageSerialNum).start();
                        } else {
                            handler.sendEmptyMessage(0);
                            String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactOptActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    // ページジャンプ
                                    mPageJumpFlag = true;
                                    Intent intent1 = new Intent();
                                    intent1.setClass(ContactOptActivity.this, SettingActivity.class);
                                    startActivity(intent1);
                                }
                            });
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     *
     * @param pLsContactListDto
     */
    private void viewContactList(List<ContactListDto> pLsContactListDto) {
        Log.i(TAG, "ContactOptActivity_viewContactList");
        ContactOptAdapter contactOptAdapter = new ContactOptAdapter(ContactOptActivity.this, R.layout.activity_contact_opt_item, pLsContactListDto);
        mContactList.setAdapter(contactOptAdapter);
        mContactList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mIntent.putExtra(Constants.KEY_CONTACT_OPT, pLsContactListDto.get(i));
                mIntent.putExtra("position", mPosition);
                setResult(REQUEST_CODE, mIntent);
                // ページジャンプ
                mPageJumpFlag = true;
                finish();
            }
        });
    }

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (0 == msg.what) {
                if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                    mDealWithWaitingDlg.dismiss();
                }
            } else if (msg.what == PAGE_EDIT_REOPEN) {
                if (!mEditReopening) {
                    // 非ページジャンプ編集が再び開きます
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(ContactOptActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mViewProcess = Constants.SEND_KID_IS_USING;
                    new BusinessThread(Constants.SEND_KID_IS_USING,
                            mParentBleTransfer,
                            mKidInfoEntity,
                            null,
                            mPageSerialNum).start();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                    mEditReopening = true;
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Log.i(TAG, "ContactOptActivity_onActivityResult");
        if (requestCode == REQUEST_CODE2) {
            // ブロードキャストの再登録
            initReceiver();
            // Dlg
            String message = "キッズケータイから情報を取得しています...";
            mDealWithWaitingDlg = new DealWithWaitingDlg(ContactOptActivity.this, R.style.commonDlg, message, true);
            mDealWithWaitingDlg.show();
            // init
            JSONObject jsonObject = new JSONObject();
            try{
            jsonObject.put("method","getContacts");
            jsonObject.put("data",JSONObject.NULL);
            }catch (JSONException ex){
                Log.e(TAG,ex.getMessage());
            }
            mViewProcess = Constants.SEND_KID_GET_INFO;
            new BusinessThread(Constants.SEND_KID_GET_INFO, mParentBleTransfer, mKidInfoEntity, jsonObject, mPageSerialNum).start();
        }
    }
    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }
    /**
     * 前のページに戻る(値なし)
     */
    public void backActivity(View view) {
        Log.i(TAG, "ContactOptActivity_backActivity");
        // ページジャンプ
        mPageJumpFlag = true;
        ContactOptActivity.this.finish();
    }
}
